package com.microservice.product.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.microservice.common.R;
import com.microservice.product.entity.ProductEntity;
import com.microservice.product.mapper.ProductMapper;
import com.microservice.product.param.ProductReduceParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * write something please~
 *
 * @author huangrz
 * @since 2021/9/14
 **/
@Slf4j
@Service
public class ProductService extends ServiceImpl<ProductMapper, ProductEntity> {

    @Retryable(value = Throwable.class, backoff = @Backoff(value = 1), maxAttempts = 50)
    public R<Boolean> reduce(ProductReduceParam param) {
        ProductEntity productEntity = getById(param.getId());
        if (productEntity.getCount() - param.getCount() <= 0) {
            return R.fail("库存不足！");
        }
        if (baseMapper.reduce(param.getId(), param.getCount(), productEntity.getVersion()) == 0) {
            throw new RuntimeException();
        } else {
            return R.ok(true);
        }
    }

    @Recover
    public R<Boolean> reduceRecover(ProductReduceParam param) {
        log.error("product reduce retry failure: {}", param.toString());
        return R.ok(false);
    }
}
